<template>
	<view>
		<Navbar></Navbar>
		<!-- 基础信息 -->
		<Info :data="personData" :isPromoter="isPromoter" @onEditUserInfo="onEditUserInfo" @chooseThank="chooseThank" @switchThanksList="switchThanksList"></Info>
		<view style="height: 200rpx;"></view>
		<view class="bottom_icon_box" v-if="!isPromoter">
			<view class="u-flex-col u-row-center u-col-center u-color-gray" @click="goBack">
				<u-icon name="fanhui" custom-prefix="custom-icon" size="40" color="#868B9A"></u-icon>
				<view>返回</view>
			</view>
			<view class="u-flex-col u-row-center u-col-center" @click="openShare">
				<u-icon name="share-fill" color="#B3723E" size="40"></u-icon>
				<view class="u-color-puce">分享</view>
			</view>
			<view class="addBtn" @click="callMobile" v-if="isFriend || isExhibitionShow">联系</view>
			<view class="addBtn" @click="addPerson" v-else>加好友</view>
		</view>
		<view class="bottom_box" v-else>
			<view class="returnBtn" @click="goBack">返回</view>
			<view class="shareBtn" @click="openShare">分享</view>
		</view>
		
		<Modal :show="modal.show" :confirmText="modal.confirm" :cancelText="modal.cancel" :modalContent="modal.content" :showCancel="modal.showCancel"
			@confirm="modalConfirm" @cancel="modal.show = false"></Modal>
		
		<!-- 分享 -->
		<Share :isShowShare="shareShow" :isMoment="isPromoter" @closeShare="closeShare" @handleOpenMoment="onOpenMoment"></Share>
		
		<!-- 开屏视频 -->
		<!-- <VideoPlay :show="videoData.show" :url="videoData.url" @close="videoData.show = false">
			<template v-if="videoData.type == 1">
				<view class="learn-btn">了解更多</view>
			</template>
			<template v-else>
				<u-icon size="50" class="u-p-r-8" color="#fff" name="close-circle" />
			</template>
		</VideoPlay> -->
		
		<!-- 高级名片海报分享 -->
		<PosterImage :data="posterData" @closePosterImage="posterData.show = false"></PosterImage>
		
		<!-- 礼物感谢框 -->
		<GiftPopup :show="giftShow" :data="gift" :status="giftBtnStatus" @onCloseGift="onGiftClose" @onGiftChoose="onGiftChoose"></GiftPopup>
		
		<!-- 开通引导 -->
		<!-- <NoticePopup :show="noticeData.show" :type="noticeData.type" :time="noticeData.time" @onRenew="onRenew" @onCloseNotice="noticeData.show = false"></NoticePopup>	 -->
	</view>
</template>

<script>
	import Navbar from '@/components/Navbar.vue'
	import Info from './component/Info.vue'
	import Trends from './component/Trends.vue'
	import Modal from '@/components/Modal.vue'
	import Exhibition from '@/components/Exhibition.vue'
	import VideoPlay from '@/components/VideoPlay.vue'
	import NoticePopup from '@/components/NoticePopup.vue'
	import PosterImage from '@/components/PosterImage.vue'
	import GiftPopup from '../components/GiftPopup.vue'
	import Share from '@/teaBureau/components/Share.vue'
	import { userFriendDetail, userInfo, singleIntegral, businessCardApply, dynamicInfo, userExhibitionStatus, userExhibitionRecord, giftList, userGiveGift, userExhibitionMenu, createOrder, generateOrderSn, userCompanyQrcode } from '@/network/api.js'
	import { getFindSupplyDetail } from '@/network/demand.js'
	import { formatDate, presidentClass, call, formatContent, pointTransform, InitScene } from '@/utils/index.js'
	import share from '@/mixins/share.js'
	export default {
		mixins: [share],
		components: {
			Navbar,
			Info,
			Trends,
			Modal,
			Share,
			Exhibition,
			VideoPlay,
			NoticePopup,
			GiftPopup,
			PosterImage
		},
		data(){
			return{
				personId: '', // 当前展厅用户id
				inviterId: '',
				userId: uni.getStorageSync("user_id"),
				personData:{},
				trendList:[],
				modal: {
					show: false,
					showCancel: true,
					confirm: '确定',
					cancel: '取消',
					content: '',
					type: 1 // 1 添加好友流程  2 展厅流程  // 3 注册
				},
				tabsData:{
					current: 0,
					list: [{name:'公司'},{name:'动态'}]
				},
				isPromoter: false, // 判断是否是用户自己的详情页
				isFriend: false, // 判断是否好友关系
				shareShow: false,
				isExhibitionShow: false, // 是否展厅高级展厅
				exhibitionData: {},// 高级展厅信息
				videoData: {
					show: false,
					type: 1, // 1开屏 2介绍
					url: ''
				},
				noticeData:{
					show: false,
					type: 0,
					time: ''
				},
				giftShow: false,
				gift:{
					list: [],
					checkId: 0,
					checkNum: 0,
					text: '',
					isAnonymous: false
				},
				posterData:{
					show: false,
					image: ''
				},
				giftBtnStatus: true
			}
		},
		async onLoad(options){
			await this.$onLaunched
			if (options.scene) {
				options.id = InitScene(options.scene).inviterId
				options.inviterId = InitScene(options.scene).inviterId
			}
			this.userId = uni.getStorageSync("user_id")
			if(this.userId == options.id){
				this.isPromoter = true
				this.isFriend = true
			}
			this.personId = options.id
			this.onGetFriendDetail()
			// this.onGetDynamicInfo()
			this.onGetUserExhibition(false)
			if(options.inviterId){
				this.inviterId = options.inviterId
			}
		},
		methods:{
			onRecord(val){
				const params = {
					type: val,
					company_id: this.exhibitionData.company_id,
					user_id: this.userId,
					reference_id: this.inviterId
				}
				userExhibitionRecord(params)
			},
			async onGetFriendDetail(id){
				const params = {
					user_id: this.personId,
					from_user_id: this.userId
				}
				const res = await userFriendDetail(params)
				res.data.president_status = parseInt(res.data.president_status)
				res.data.president_class = presidentClass(res.data.president_status)
				if([6,7,8,'6','7','8'].includes(uni.getStorageSync("president_status"))){
					res.data.phone = res.data.phone
				}else if(res.data.is_exchange == 0 && Number(id) !== this.userId){
					res.data.phone = '***********'
				}
				if(res.data.is_friend == 1){
					this.isFriend = true
				}
				res.data.businessImageList = []
				if(res.data.bussiness_card.img_text[0]){
					res.data.bussiness_card.img_text.map(imgItem=>{
						res.data.businessImageList.push({image: imgItem})
					})
				}
				/* if (res.data.bussiness_card.video_text[0]) {
					this.videoData.type = 1
					this.videoData.url = res.data.bussiness_card.video_text[0]
					this.videoData.show = true
				} */
				res.data.number = pointTransform(res.data.number)
				res.data.hometown = res.data.complete_address.substring(0, res.data.complete_address.indexOf("区") + 1)
				this.personData = res.data
				this.mixinsShare.page = `/teaBureau/teaPersonDetail/teaPersonDetail?id=${res.data.id}&inviterId=${this.userId}`
				this.mixinsShare.title = `推荐名片：${res.data.name}`
				this.mixinsShare.image = res.data.head_img
			},
			async onGetUserExhibition(val){
				if(val){
					return
				}else{
					// 名片主的信息
					const res = await userExhibitionStatus({
						userid: this.personId
					})
					this.exhibitionData = res.data
					if ([1].includes(res.data.is_have)) {
						if (res.data.video && res.data.video.url) {
							this.videoData.type = 1
							this.videoData.url = res.data.video.url
							this.videoData.show = true
						}
						this.isExhibitionShow = true
					}
					if(res.data.status == 1 && !this.isPromoter){
						this.onRecord(1)
					}
				}
				
				// 访问者的信息
				const userRes = await userExhibitionStatus({
					userid: uni.getStorageSync("user_id")
				})
				if(!this.isPromoter && userRes.data.is_have == 1){
					return
				}else{
					switch(userRes.data.is_have){
						case 0:
						case 2:
						    this.noticeData.type = 2
							break;
						case 1:
						    this.noticeData.type = 3
							this.noticeData.time = userRes.data.deadline_time.slice(0,10)
							break;
					}
					this.noticeData.show = true	
				}		
			},
			async onGetDynamicInfo(){
				const res = await dynamicInfo({user_id:this.personId})
				if(res.data.length > 0){
					res.data.map(item=>{
						if([6,7].includes(item.result_type)){
							switch(item.pay_type){
								case "1":
								    item.pay_name = '免费'
									break;
								case "2":
								    item.pay_name = `${parseInt(item.price)}元`
									break;
								case "3":
								    item.pay_name = `${parseInt(item.price)}积分`
									break;
							}
							item.starting_time = `${item.start_time.slice(0,16)}-${item.end_time.slice(11,16)}`
						}else{
							item.start_time = formatDate(item.start_time)
							item.end_time = formatDate(item.end_time)
						}
						if(item.label){
							item.label = item.label.split("#").filter(item=>item !== null && item !== undefined && item)
						}
					})
					this.trendList = res.data
				}
			},
			async onOpenMoment(){
				const params = {
					user_id: this.personId
				}
				const res = await userCompanyQrcode(params)
				this.posterData.image = res.data.url
				this.posterData.show = true
			},
			onTabsChange(val){
				this.tabsData.current = val
			},
			onViewVideo(val) {
				this.videoData.type = 2
				this.videoData.url = val.url
				this.videoData.show = true
			},
			openSwiper(val) {
				let list = []
				val.list.map(item=>list.push(item.image))
				uni.previewImage({
					current: val.index,
					urls: list
				})
			},
			goBack(){
				if(this.momentJudge()){
					let pages = getCurrentPages()
					let prePage = pages[pages.length - 2]
					if (prePage) {
						uni.navigateBack({
							delta: 1
						})
					} else {
						uni.switchTab({
							url: "/pages/home/home"
						})
					}
				}
			},
			openShare(){
				if(this.momentJudge()){
					this.shareShow = true
				}
			},
			closeShare() {
				this.shareShow = false
			},
			addPerson(){
				if(this.momentJudge()){
					if([0,'0'].includes(uni.getStorageSync("user_status"))){
						this.modal.content = '部分功能需注册解锁，注册后即可体验完整服务'
						this.modal.confirm = '立即注册'
						this.modal.type = 3
						this.modal.show = true
					}else{
						this.modal.content = `交换名片，对方同意后交换成功`
						this.modal.confirm = '确定'
						this.modal.type = 1
						this.modal.show = true
					}
				}
			},
			callMobile(){
				if(this.momentJudge()){
					this.onRecord(2)
					call(this.personData.phone)
				}
			},
			onEditUserInfo(){
				uni.setStorageSync("inviterUrl",`teaBureau/teaPersonDetail/teaPersonDetail?id=${this.personId}`)
				uni.redirectTo({
					url: "/pages/register/register?isEdit=1"
				})
			},
			async onRenew(){
				/* 续费高级展厅 */
				const res = await userExhibitionMenu({key:5})
				const orderSnRes = await generateOrderSn()
				const params = {
					type: "exhibition",
					order_sn: orderSnRes.data.order_sn,
					userid: uni.getStorageSync("user_id"),
					key: res.data.list.key,
					price: res.data.list.value
				}
				const _this = this
				const creRes = await createOrder(params)
				await uni.requestPayment({
					provider: "wxpay",
					appId: creRes.data.order_str.appId,
					timeStamp: creRes.data.order_str.timeStamp,
					nonceStr: creRes.data.order_str.nonceStr,
					package: creRes.data.order_str.package,
					signType: creRes.data.order_str.signType,
					paySign: creRes.data.order_str.paySign,
					success() {
						uni.showToast({
							title: "续费成功",
							icon: "none"
						})
						_this.onGetUserExhibition(true)
					}
				})
			},
			async chooseThank(){
				/* 打开感谢框 */
				const res = await giftList()
				res.data.map(item=>{
					item.check = false
				})
				res.data.push({id:9527,name:'自定义积分',num: '',check: false})
				this.gift.list = res.data
				this.giftShow = true
			},
			async onGiftChoose(val){
				if(val.checkNum){
					this.giftBtnStatus = false
					const params = {
						user_id: this.personId,
						give_user_id: this.userId,
						num: val.checkNum,
						content: val.text,
						is_anonymous: val.isAnonymous ? 1: 2
					}
					const res = await userGiveGift(params)
					this.onGetFriendDetail()
					this.gift.checkId = 0
					this.gift.checkNum = 0
					this.gift.text = ''
					this.gift.isAnonymous = true
					this.giftBtnStatus = true
					this.giftShow = false
					uni.showToast({
						title: "提交成功",
						icon: "none"
					})
				}else{
					uni.showToast({
						title: "请选择积分",
						icon: "none"
					})
				}
			},
			onGiftClose(){
				this.giftBtnStatus = true
				this.giftShow = false
			},
			switchThanksList(){
				uni.navigateTo({
					url: "/teaBureau/teaThanksList/teaThanksList?id=" + this.personId
				})
			},
			onEditConvention(){
				userExhibitionStatus({
					userid: this.userId
				}).then(res => {
					switch (Number(res.data.status)) {
						case -2:
						    if(res.data.is_have == 1){
								uni.navigateTo({
									url: "/operate/seniorForm/seniorForm?type=2"
								})
							}
							break;
						case -1:
							this.modal.content = "您的申请未通过"
							this.modal.confirm = "重新申请"
							this.modal.show = true
							this.modal.type = 2
							break;
						case 0:
						case 2:
							this.modal.content = "您已提交资料，系统审核中，请耐心等候"
							this.modal.confirm = "确定"
							this.modal.show = true
							this.modal.type = 2
							break;
						case 1:
						    uni.setStorageSync("inviterUrl",`teaBureau/teaPersonDetail/teaPersonDetail?id=${this.personId}`)
							if(res.data.is_have == 1){
								uni.navigateTo({
									url: "/operate/seniorForm/seniorForm?type=2"
								})
							}else{
								uni.navigateTo({
									url: "/operate/seniorForm/seniorForm?type=1"
								})
							}
							break;
					}
				})
			},
			modalConfirm(){
				if(this.momentJudge()){
					switch(this.modal.type){
						case 1:
						    userInfo({user_id: this.userId}).then(res=>{
						    	let integral = res.data.integral  // 用户积分
						    	const params = {
						    		key: "ExchangeCards",
						    		type: 0
						    	}
						    	singleIntegral(params).then(singleRes=>{
						    		let singleIntegral = singleRes.data.value
						    		if(parseInt(integral) < parseInt(singleIntegral)){
						    			uni.showToast({
						    				title: "积分不足",
						    				icon: "none"
						    			})
						    		}else{
						    			const applyParams = {
						    				user_id: this.userId,
						    				from_user_id: this.personData.id
						    			}
						    			businessCardApply(applyParams).then(applyRes=>{
						    				uni.showToast({
						    					title: `${applyRes.msg}`,
						    					icON: "none"
						    				})
						    			})
						    		}
						    	})
						    })
							break;
						case 2:
						    userExhibitionStatus({userid: this.userId}).then(res=>{
						    	if(res.data.status == -1 && [1].includes(res.data.is_have)){
						    		uni.setStorageSync("inviterUrl",`teaBureau/teaPersonDetail/teaPersonDetail?id=${this.personId}`)
						    		uni.navigateTo({
						    			url: "/operate/seniorForm/seniorForm?type=2"
						    		})
						    	}
						    	if(res.data.status == -1 && [0,2].includes(res.data.is_have)){
						    		uni.navigateTo({
						    			url: "/operate/exhibition/exhibition"
						    		})
						    	}
						    	if(res.data.status == 1 && [1].includes(res.data.is_have)){
						    		uni.navigateTo({
						    			url: "/operate/seniorForm/seniorForm?type=2"
						    		})
						    	}
						    	if(res.data.status == 1 && [0,2].includes(res.data.is_have)){
						    		uni.navigateTo({
						    			url: "/operate/seniorForm/seniorForm?type=1"
						    		})
						    	}
						    })
							break;
						case 3:
						    uni.setStorageSync("inviterUrl",`teaBureau/teaPersonDetail/teaPersonDetail?id=${this.personId}`)
						    uni.redirectTo({
						    	url: "/pages/register/register"
						    })
							break;
					}
					this.modal.show = false
				}else{
					this.modal.show = false
				}
			},
			momentJudge() {
				if (!this.userId) {
					uni.showToast({
						icon: "none",
						duration: 2000,
						title: "请先点击下方'前往小程序'方可对接",
					})
					return false
				} else {
					if(uni.getStorageSync("user_isBlack") == 0){
						return true
					}else{
						this.modal.content = '当前用户权限受限，请联系系统管理员'
						this.modal.confirmText = '确定'
						this.modal.show = true
						return false
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.addBtn {
		width: 400rpx;
		background: #F96257;
		color: #fff;
		border-radius: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.returnBtn{
		flex:1;
		height: 80rpx;
		background: #ccc;
		color: #fff;
		border-radius: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 26rpx;
		margin-right: 40rpx;
	}
	
	.shareBtn{
		flex:1;
		height: 80rpx;
		background: #B3723E;
		color: #fff;
		border-radius: 50rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 26rpx;
	}
	
	.learn-btn {
		background: #B3723E;
		color: #fff;
		padding: 18rpx 120rpx;
		border-radius: 50rpx;
		font-size: 26rpx;
	}
</style>